<script setup>
import {onMounted, ref} from 'vue';
import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {router} from '@/router/index.js';
import ratingForm from '@/components/RatingForm.vue';

const orderStatus = ref({ '0': '全部预约', '1': '已预约', '2': '已试驾', '3': '已过期' });
const appointments = ref([]);
const activeName = ref('0');

const goShopping = () => { router.push("/").catch(error => error); }

const handleClick = (tab) => {
  queryByStatus(tab.props.name);
};
const queryByStatus = (status) => {
  axios.get(`/appointments/queryByStatus?status=${status}`)
      .then((resp) => {
        appointments.value = resp.data.map(appointment => {
          const appointmentDate = new Date(appointment.appointmentDate);
          const currentDate = new Date();
          const diffInDays = Math.floor((currentDate - appointmentDate) / (1000 * 60 * 60 * 24));
          if (diffInDays > 2 && appointment.status !== 3) {
            axios.post(`/appointments/updateStatus/${appointment.appointmentId}`, { status: 3 })
                .then(() => {
                  appointment.status = 3;
                })
          }
          return appointment;
        });
      })
      .catch((error) => {
        ElMessage({ type: 'error', message: error, showClose: true })
      });
};

const getOrderButtons = (orderStatus) => {
  switch (orderStatus) {
    case 1:
      return [
        { label: '取消预约', type: 'danger', action: remove },
        { label: '车辆详情', type: 'primary', action: details },
      ];
    case 2:
      return [
        { label: '去评价', type: 'success', action: review },
        { label: '车辆详情', type: 'primary', action: details },
        { label: '删除记录', type: 'warning', action: remove },
      ];
    case 3:
      return [
        { label: '已过期', type: 'danger',   action: expired },
        { label: '车辆详情', type: 'primary', action: details },
        { label: '删除记录', type: 'warning', action: remove },
      ];
    default:
      return [];
  }
};
const details = (row) => {
  const productId = row.productId;
  router.push({ name: 'carDetails', params: { id: productId } })
};


const expired = (row) => {
  ElMessage.info("该预约已过期");
};

const remove = (row) => {
  ElMessageBox.confirm(
      `您确定要取消【${row.name}】的预约信息吗？`, '警告',
      {
        confirmButtonText: '确 认',
        cancelButtonText: '取 消',
        type: 'warning',
      }
  ).then(() => {
    return axios.delete(`/appointments/remove/${row.appointmentId}`);
  }).then(() => {
    ElMessage({ type: 'success', message: '取消成功', showClose: true })
    queryByStatus('0');
  }).catch(errorMsg => {
    ElMessage({ type: 'info', message: errorMsg, })
  })
};

const review = (orderId) => {
  const productId = orderId.productId;
  router.push({ name: 'ratingForm', params: { id: productId } });
};

const calculateMonthlyPayment = (price) => {
  // 确保 price 是有效的数字
  if (typeof price === 'number' && !isNaN(price)) {
    const interestRate = 0.05;
    const months = 120;
    const monthlyRate = interestRate / 12;
    const monthlyPayment = (price * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -months));
    return monthlyPayment > 0 ? monthlyPayment.toFixed(2) : '0.00';
  }
  return '0.00'; // 如果 price 不是有效的数字，返回默认值
};


onMounted(() => {
  queryByStatus('0');
});
</script>


<template>
  <el-container>
    <el-header class="header-center">
      <div>预约试驾</div>
    </el-header>
    <el-main>
      <el-card class="shopping-appo">
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <!-- 显示所有订单的状态 -->
          <el-tab-pane :label="value" :name="key" v-for="(value, key, index) in orderStatus" :key="index">
            <!-- 显示订单明细 -->
            <div v-if="appointments.length > 0">
              <div v-for="appointment in appointments" :key="appointment.appointmentId" class="order-middle">
                <el-descriptions>
                  <el-descriptions-item label="类型">{{ appointment.categoryName }}</el-descriptions-item>
                  <el-descriptions-item label="价格">¥{{ appointment.price.toFixed(2) }} 起</el-descriptions-item>
                  <el-descriptions-item label="月付">¥{{ calculateMonthlyPayment(appointment.price) }} 起</el-descriptions-item>
                  <el-descriptions-item label="车辆能源">{{ appointment.energy }}</el-descriptions-item>
                  <el-descriptions-item label="座位数">{{ appointment.seatCount }}</el-descriptions-item>
                </el-descriptions>

                <el-table :data="[appointment]" style="width: 100%" border>
                  <el-table-column prop="name" label="车名" >
                    <template #default="{ row }">{{ row.name }}</template>
                  </el-table-column>
                  <el-table-column prop="imgs" label="图片" >
                    <template #default="{ row }">
                      <el-image style="height: 120px;"
                                :src="$urlImage + row.imgs"
                                fit="contain">
                      </el-image>
                    </template>
                  </el-table-column>
                  <el-table-column prop="appointmentDate" label="预约时间">
                    <template #default="{row}">{{(row.appointmentDate)}}</template>
                  </el-table-column>
                </el-table>

                <div class="order-footer">
                  <!-- 根据订单状态决定显示的按钮 -->
                  <el-button
                      v-for="button in getOrderButtons(appointment.status)"
                      :key="button.label"
                      size="small"
                      round
                      :type="button.type"
                      :icon="button.icon"
                      @click="() => button.action(appointment)">
                    {{ button.label }}
                  </el-button>
                </div>
              </div>

            </div>
            <!-- 没有内容的显示 -->
            <div v-else>
              <el-empty description="预约是空的"></el-empty>
              <el-button type="primary" style="width: 150px" @click="goShopping">
                去首页
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </el-main>
  </el-container>
</template>

<style scoped>
.shopping-appo {
  margin: 15px;
  border-radius: 10px;
}
.header-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%; /* 确保高度占满整个 header */
}

.order-middle {
  border-radius: 5px;
  border: 1px solid #e4e7ed;
  margin-bottom: 20px;
  padding: 10px;
  box-shadow: 0 5px 10px -5px rgba(0, 0, 0, 0.5);
}

.order-footer {
  margin-top: 10px;
  margin-bottom: 5px;
}
</style>